//
//  HomeViewController.swift
//  TianTianBiTing
//
//  Created by Gox mac 2 on 2018/12/17.
//  Copyright © 2018 Gox_WallyDiao. All rights reserved.
//

import UIKit

let HomeSearch = 0
let HomeTopBanner = 1
let HomeItems = 2
//let HomeCentreBanner = 3
//let HomeBottomBanner = 4
let HomeHotListen = 3
let HomeOtherListen = 4

class HomeViewController: HomeBaseVC {
    
    private let HomeOthersListenCellID = "HomeOthersListenCell"
    
    lazy var tableView: TTTableView = {
        let tableView = TTTableView.init(frame: FRAME_CGFloat(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - OFFSET_TOP - OFFSET_BOTTOM), style: UITableView.Style.plain)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = UIColor.white
        tableView.separatorStyle = UITableViewCell.SeparatorStyle.none
        tableView.bounces = true
        tableView.showsVerticalScrollIndicator = false
        tableView.showsHorizontalScrollIndicator = false
        tableView.register(HomeOthersListenCell.self, forCellReuseIdentifier: HomeOthersListenCellID)
        tableView.tableFooterView = UIView.init(frame: .zero)
        return tableView
    }()
    
    var redView: TimeRedPacketView?
    
    lazy var topBannerviewModel: [TopBannerImagesModel] = [{
        return TopBannerImagesModel()
        }()]
    lazy var itemsModel: [CentreItemImagesModel] = [{
        return CentreItemImagesModel()
        }()]
    lazy var centreBannerviewModel: [CentreBannerImagesModel] = [{
        return CentreBannerImagesModel()
        }()]
    lazy var hotListenViewModel: [ListenListModel] = [{
        return ListenListModel()
        }()]
    lazy var otherListenViewModel: [OtherListenModel] = [{
        return OtherListenModel()
        }()]
    
    lazy var playView:UIImageView = {
        let view = UIImageView.init(frame: FRAME_CGFloat(SCREEN_WIDTH - 100, SCREEN_HEIGHT - OFFSET_BOTTOM - OFFSET_TOP - 146, 74, 74))
        view.layer.borderWidth = 1
        view.layer.borderColor = TabbarTintColor.cgColor
        view.layer.cornerRadius = 37
        view.isUserInteractionEnabled = true
        view.layer.masksToBounds = true
        view.isHidden = true
        
        let view1 = UIImageView.init(frame: FRAME_CGFloat(0, 0, 74, 74))
        view1.image = IMAGE(name: "playing")
        view1.layer.borderWidth = 1
        view1.layer.borderColor = TabbarTintColor.cgColor
        view1.layer.cornerRadius = 37
        view1.addGestureRecognizer(UITapGestureRecognizer(target:self, action:#selector(toPlay)))
        view1.isUserInteractionEnabled = true
        view1.layer.masksToBounds = true
        view.addSubview(view1)
        
        return view
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationController?.navigationBar.shadowImage = UIImage.init()
        self.navigationItem.title = "天天必听"
        self.view.addSubview(self.tableView)
        self.tableView.initMjHeaderWithOffest(0) { (tableView) in
            self.setData()
        }
        
        setDate()
        setData()
        
        self.view.addSubview(self.playView)

        

    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if TTAudioPlayer.imageUrl != nil {
            self.playView.sd_setImage(with: URLSTR(StringIncludeChineseToString(TTAudioPlayer.imageUrl ?? "")), completed: nil)
        }
        if TTAudioPlayer.state().rawValue == 3 {
            self.playView.isHidden = false
            self.roundAnimation()
        } else if TTAudioPlayer.state().rawValue == 9 {
            self.playView.isHidden = false
            self.stopRoundAnimation()
        } else {
            self.playView.isHidden = true
            self.stopRoundAnimation()
        }
        
        self.redView = TimeRedPacketView.init(frame: FRAME_CGFloat(SCREEN_WIDTH - 80, 300, 80, 80), viewName: "首页")
        self.view.addSubview(self.redView!)
        
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
        self.redView?.removeFromSuperview()
    }
    
}

//  MARK: - ###### 数据 ######
extension HomeViewController {
    func setDate() {
        if !String.getUserIdToString() {
        } else {
            HomeRequestModel.uploadingNowDate(parameters: ["userId":String.getUserId(), "operationTypeId":1]) { (suc) in
            }
            
            HomeRequestModel.UpdateJPushId(parameters: ["jpushId": String.getJpushId(), "userId": String.getUserId()]) { (sucess) in
                
            }
            
            openBackView()
        }
    }
    
    func setData() {
        UserDefaults.standard.set(42 , forKey: UserId)
//        HomeRequestModel.getIOSAudit { (success, user) in // 46158
//            if success {
//                UserDefaults.standard.set(user , forKey: UserId)
//            }
//            
//        }
        HomeRequestModel.loadHomeTopBannerData { (success, message, model) in
            if success && model != nil {
                self.topBannerviewModel = model!
                self.tableView.reloadSections(NSIndexSet(index: 1) as IndexSet, with: .automatic)
            }
        }
        
        HomeRequestModel.loadHomeItemsData { (success, message, model) in
            if success && model != nil {
                self.itemsModel = model!
                self.tableView.reloadSections(NSIndexSet(index: 2) as IndexSet, with: .automatic)
            }
        }
        
        HomeRequestModel.loadListenListData(categoryId: 41, parameters:["startPoint":1,"maxPage":10]) { (success, message, model) in
            if success && model != nil {
                self.hotListenViewModel = model!
                self.tableView.reloadSections(NSIndexSet(index: 3) as IndexSet, with: .automatic)
            }
            self.tableView.endXWHeadRefreshing()
        }
        
        HomeRequestModel.loadListenListData(categoryId: 41, parameters:["userId":String.getUserId(),"startPoint":1,"maxPage":9999]) { (success, message, model) in
            if success && model != nil {
                self.hotListenViewModel = model!
                self.tableView.reloadSections(NSIndexSet(index: 3) as IndexSet, with: .automatic)
            }
            self.tableView.endXWHeadRefreshing()
        }
        
        HomeRequestModel.loadOtherListenData { (success, message, model) in
            if success && model != nil {
                self.otherListenViewModel = model!
                self.tableView.reloadSections(NSIndexSet(index: 4) as IndexSet, with: .automatic)
            }
        }
        
    }
}

//  MARK: - ###### UI ######
extension HomeViewController {
    func setBackView() {
        let backView = EveryDaySignView.init(frame: FRAME_CGFloat(0, OFFSET_TOP, SCREEN_WIDTH, SCREEN_HEIGHT - OFFSET_TOP))
        backView.checkBlock = { () in
            let vc = SignRedVc()
            PUSHVIEWCONTROLLER(vc)
        }
        backView.signBlock = { () in
            backView.removeFromSuperview()
        }
        UIApplication.shared.keyWindow?.addSubview(backView)

    }
    
    func roundAnimation() {
        let rotationAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
        rotationAnimation.toValue = NSNumber(value: M_PI * 2.0)
        rotationAnimation.duration = 10
        rotationAnimation.isCumulative = true
        rotationAnimation.repeatCount = 99999999
        self.playView.layer.add(rotationAnimation, forKey: "rotationAnimation")
        
    }
    
    func stopRoundAnimation() {
        self.playView.layer.removeAllAnimations()
    }
}

//  MARK: - ###### 事件 ######
extension HomeViewController {
    @objc func leftBtnAction() {
        let vc = NewsVc()
        ISLOGIN_PUSHVIEWCONTROLLER(vc)
    }
    
    @objc func searchAction(seatchTap:UITapGestureRecognizer) {
        let vc = SearchVC()
        vc.searchStr = ""
        PUSHVIEWCONTROLLER(vc)
    }
    
    @objc func toPlay() {
        let playVc = PlayVC()
        playVc.id = TTAudioPlayer.programId
        PUSHVIEWCONTROLLER(playVc)
    }
    
    func openBackView() {
        let userDefault = UserDefaults.standard
        let nowDate = Date()
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd"
        let nowStr:String = dateFormatter.string(from: nowDate)
        if userDefault.string(forKey: "nowDate") != nowStr {
            setBackView()
        }
        userDefault.set(nowStr, forKey: "nowDate")
    }
    
}

//  MARK: - ###### 协议 ######
extension HomeViewController: UITableViewDelegate, UITableViewDataSource, HomeTopBannerViewDelegate, HomeHotListenViewDelegate, HomeOthersListenCellDelegate, HomeItemsViewDelegate {
    func HomeTopBannerViewClick(clickUrl: String, target: String) {
        print(target)
        if target == "program" {
            let playVc = PlayVC()
            playVc.id = Int(clickUrl)!
            ISLOGIN_PUSHVIEWCONTROLLER(playVc)
        } else if target == "url" {
            let vc = WebVc()
            vc.urlString = clickUrl
            vc.modalTransitionStyle = .crossDissolve
            self.present(vc, animated: true, completion: nil)
        }
    }
    
    func HomeItemsViewClick(target: String, name: String, clickUrl: String) {
        if target == "category" {
            let listenVc = ListenListVC()
            listenVc.id = Int(clickUrl)!
            listenVc.titleStr = name
            PUSHVIEWCONTROLLER(listenVc)
        } else if target == "xcx" {
            TTAlertView.showMessage(message: "暂未上线，尽请期待！", second: 2)
//            let launchMiniProgramReq = WXLaunchMiniProgramReq.object()
//            launchMiniProgramReq?.userName = WxUserName
//            launchMiniProgramReq?.path = WxCYCPath
//            launchMiniProgramReq?.miniProgramType = .release
//            WXApi.send(launchMiniProgramReq)
        } else if target == "url" {
            let vc = WebVc()
            vc.urlString = clickUrl
            vc.modalTransitionStyle = .crossDissolve
            self.present(vc, animated: true, completion: nil)
        }
    }
    
    func HomeOthersListenHeaderCellClick(id: Int, name:String) {
        let listenVc = ListenListVC()
        listenVc.id = id
        listenVc.titleStr = name
        PUSHVIEWCONTROLLER(listenVc)
    }
    
    func HomeHotListenHeadViewClick(id: Int) {
        let listenVc = ListenListVC()
        listenVc.id = id
        listenVc.titleStr = "热听榜单"
        PUSHVIEWCONTROLLER(listenVc)
    }
    
    
    func HomeOthersListenCellClick(id: Int) {
        let playVc = PlayVC()
        playVc.id = id
        ISLOGIN_PUSHVIEWCONTROLLER(playVc)
    }
    
    func HomeHotListenViewClick(id: Int) {
        let playVc = PlayVC()
        playVc.id = id
        ISLOGIN_PUSHVIEWCONTROLLER(playVc)
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 5
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        switch section {
        case HomeOtherListen:
            return self.otherListenViewModel.count
        default:
            return 0
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        switch indexPath.section {
        case HomeOtherListen:
            return 217
        default:
            return 0
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        switch indexPath.section {
        case HomeOtherListen:
            let cell = tableView.dequeueReusableCell(withIdentifier: HomeOthersListenCellID) as! HomeOthersListenCell
            cell.modelList = self.otherListenViewModel[indexPath.row]
            cell.delegate = self
            cell.selectionStyle = .none
            return cell
        default:
            return UITableViewCell.init()
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        switch indexPath.section {
        case HomeSearch:
            print("0")
        case HomeTopBanner:
            print("1")
        case HomeItems:
            print("2")
//        case HomeCentreBanner:
//            print("3")
//        case HomeBottomBanner:
            print("4")
        case HomeHotListen:
            print("5")
        case HomeOtherListen:
            print("6")
        default:
            print("other")
        }
        
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        switch section {
        case HomeSearch:
            return 40
        case HomeTopBanner:
            return 158
        case HomeItems:
            return 100
//        case HomeCentreBanner:
//            return 100
//        case HomeBottomBanner:
//            return 25
        case HomeHotListen:
            return 370
        default:
            return 0
        }
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        switch section {
        case HomeSearch:
            let searchView = HomeSearchView.init(frame: FRAME_CGFloat(0, 0, SCREEN_WIDTH - 40, 40))
            searchView.setTitle(title: "搜索")
            searchView.isUserInteractionEnabled = true
            let searchTap = UITapGestureRecognizer(target: self, action: #selector(self.searchAction(seatchTap:)))
            searchView.addGestureRecognizer(searchTap)
            
            let imageView = UIImageView.init(frame: FRAME_CGFloat(SCREEN_WIDTH - 39, 0, 21, 28))
            imageView.image = IMAGE(name: "mine消息")
            searchView.addSubview(imageView)
            
            let bt = UIButton.init(type: .custom)
            bt.frame = FRAME_CGFloat(SCREEN_WIDTH - 40, 0, 40, 40)
            bt.addTarget(self, action: #selector(leftBtnAction), for: .touchUpInside)
            searchView.addSubview(bt)
            
            return searchView
        case HomeTopBanner:
            let topBanner = HomeTopBannerView.init(frame: FRAME_CGFloat(0, 0, SCREEN_WIDTH, 158))
            topBanner.delegate = self
            topBanner.bannerList = self.topBannerviewModel
            return topBanner
        case HomeItems:
            let itemsView = HomeItemsView.init(frame: FRAME_CGFloat(0, 0, SCREEN_WIDTH, 100), viewController: self)
            itemsView.delegate = self
            itemsView.modelList = self.itemsModel
            return itemsView
//        case HomeCentreBanner:
//            let centreBanner = HomeCentreBannerView.init(frame: FRAME_CGFloat(15, 0, SCREEN_WIDTH - 30, 100))
//            centreBanner.bannerList = centreBannerviewModel
//            return centreBanner
//        case HomeBottomBanner:
//            let bottomBanner = HomeBottomBannerView.init(frame: FRAME_CGFloat(15, 0, SCREEN_WIDTH - 30, WELFAREBANNER_HEIGHT), message: ["哈哈哈哈哈","呵呵呵呵呵"])
//            return bottomBanner
        case HomeHotListen:
            let homeHot = HomeHotListenView.init(frame: FRAME_CGFloat(0, 0, SCREEN_WIDTH, 370), viewController: self)
            homeHot.delegate = self
            homeHot.modelList = self.hotListenViewModel
            return homeHot
        default:
            return UIView.init()
        }
    }
}

